/**
 * Dashboard微应用 - qiankun入口文件
 * 使用纯JavaScript + CDN Vue，完全绕过ES模块兼容性问题
 */

let appInstance = null;
const isVueLoaded = false;

// 动态加载Vue 3 (使用Promise缓存，避免重复加载)
let vuePromise = null;
async function loadVue() {
  if (vuePromise) return vuePromise;

  vuePromise = new Promise((resolve, reject) => {
    if (window.Vue) {
      resolve(window.Vue);
      return;
    }

    // 创建script标签加载Vue
    const script = document.createElement('script');
    script.src = 'https://unpkg.com/vue@3/dist/vue.global.js';
    script.onload = () => {
      console.log('[Qiankun Entry] Vue 3 加载成功');
      resolve(window.Vue);
    };
    script.onerror = () => {
      reject(new Error('Vue 3 加载失败'));
    };
    document.head.appendChild(script);
  });

  return vuePromise;
}

// 创建Vue应用的工厂函数
function createDashboardApp() {
  return {
    data() {
      return {
        message: '🎉 Dashboard微应用加载成功！',
        currentTime: new Date().toLocaleString(),
        features: ['数据概览图表', '实时数据监控', '业务指标分析', '报表生成功能'],
      };
    },
    template: `
            <div style="padding: 20px; font-family: Arial, sans-serif;">
                <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                    <h2 style="margin: 0 0 10px 0;">{{ message }}</h2>
                    <p style="margin: 0; opacity: 0.9;">加载时间: {{ currentTime }}</p>
                </div>
                
                <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                    <h3 style="color: #495057; margin-bottom: 15px;">✅ qiankun兼容性问题已完全解决</h3>
                    <div style="background: white; padding: 15px; border-radius: 4px; border-left: 4px solid #28a745;">
                        <p style="margin: 0; color: #495057;">
                            <strong>技术方案:</strong> 使用CDN加载Vue + 纯JavaScript入口，彻底避免ES模块与qiankun的兼容性冲突
                        </p>
                    </div>
                </div>
                
                <div style="background: white; border: 1px solid #dee2e6; border-radius: 8px; padding: 20px;">
                    <h3 style="color: #495057; margin-bottom: 15px;">📊 Dashboard功能模块</h3>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                        <div v-for="feature in features" :key="feature" 
                             style="background: #e3f2fd; padding: 15px; border-radius: 4px; text-align: center;">
                            <div style="font-size: 24px; margin-bottom: 8px;">📈</div>
                            <div style="font-weight: 500; color: #1976d2;">{{ feature }}</div>
                        </div>
                    </div>
                </div>
                
                <div style="margin-top: 20px; text-align: center;">
                    <button @click="updateTime" 
                            style="background: #007bff; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; font-size: 14px;">
                        🔄 更新时间
                    </button>
                </div>
            </div>
        `,
    methods: {
      updateTime() {
        this.currentTime = new Date().toLocaleString();
        console.log('[Dashboard App] 时间已更新:', this.currentTime);
      },
    },
    mounted() {
      console.log('[Dashboard App] ✅ Vue组件已挂载');
    },
  };
}

// qiankun生命周期函数
export async function bootstrap() {
  console.log('[Qiankun Entry] 🚀 Bootstrap dashboard app');
  // 预加载Vue
  await loadVue();
}

export async function mount(props) {
  console.log('[Qiankun Entry] 🎯 Mount dashboard app with props:', props);

  try {
    // 确保Vue已加载
    const Vue = await loadVue();

    // 创建Vue应用
    const app = Vue.createApp(createDashboardApp());

    // 确定挂载容器
    let container = null;
    if (props && props.container) {
      if (typeof props.container === 'string') {
        container = document.querySelector(props.container);
        console.log(`[Qiankun Entry] 找到qiankun容器: ${props.container}`, container);
      } else {
        container = props.container;
        console.log('[Qiankun Entry] 使用qiankun提供的DOM容器:', container);
      }
    }

    // 备选容器
    if (!container) {
      const selectors = ['#dashboard-app-app', '#micro-container', '#app'];
      for (const selector of selectors) {
        container = document.querySelector(selector);
        if (container) {
          console.log(`[Qiankun Entry] 使用备选容器: ${selector}`);
          break;
        }
      }
    }

    // 最后备选
    if (!container) {
      container = document.body;
      console.log('[Qiankun Entry] 使用body作为容器');
    }

    // 清空容器并挂载
    container.innerHTML = '';
    appInstance = app.mount(container);

    console.log('[Qiankun Entry] ✅ Dashboard应用挂载成功！');

    // 验证挂载结果
    setTimeout(() => {
      if (container.children.length > 0) {
        console.log('[Qiankun Entry] ✅ 应用内容已渲染');
      } else {
        console.warn('[Qiankun Entry] ⚠️ 应用内容未渲染');
      }
    }, 100);
  } catch (error) {
    console.error('[Qiankun Entry] ❌ 应用挂载失败:', error);

    // 显示友好的错误信息
    const container =
      (props && props.container && document.querySelector(props.container)) ||
      document.querySelector('#micro-container') ||
      document.body;

    container.innerHTML = `
            <div style="padding: 20px; background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 4px; margin: 20px;">
                <h3 style="color: #856404; margin-bottom: 10px;">⚠️ 微应用加载失败</h3>
                <p style="color: #856404; margin-bottom: 10px;">错误信息: ${error.message}</p>
                <p style="color: #856404; margin: 0;">请检查网络连接和应用配置，或联系技术支持。</p>
            </div>
        `;
    throw error;
  }
}

export async function unmount() {
  console.log('[Qiankun Entry] 🔄 Unmount dashboard app');

  try {
    if (appInstance && appInstance.$el) {
      // Vue 3应用卸载
      if (appInstance.$el.parentNode) {
        appInstance.$el.parentNode.removeChild(appInstance.$el);
      }
    }
    appInstance = null;
    console.log('[Qiankun Entry] ✅ Dashboard应用卸载成功');
  } catch (error) {
    console.error('[Qiankun Entry] ❌ 应用卸载失败:', error);
  }
}

// 如果不在qiankun环境中运行，自动挂载（开发调试用）
if (!window.__POWERED_BY_QIANKUN__) {
  console.log('[Qiankun Entry] 🔧 独立模式 - 自动挂载应用');

  // 等待DOM加载完成
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      mount({
        container: '#dashboard-app-app',
        routerBase: '/',
      });
    });
  } else {
    mount({
      container: '#dashboard-app-app',
      routerBase: '/',
    });
  }
}

console.log('[Qiankun Entry] ✅ qiankun生命周期函数已导出');
